package com.woniu.myRedisTest;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 自定义的redis的小demo模拟服务器拦截客户端的消息
 *
 * @author WenXin
 * @version 1.0
 * @description: TODO
 * @date 2022/9/13 19:50
 */
public class MyJedisDemo {
    Socket socket;

    public static void main(String[] args) throws IOException {
//        MyTedisDemo.send();
//        ServerSocket serverSocket = new ServerSocket(6379);
//        Socket accept = serverSocket.accept();
//        InputStream inputStream = accept.getInputStream();
//        byte[] bytes = new byte[1024];
//        inputStream.read(bytes);
//        System.out.println(new String(bytes, "utf-8"));
//        accept.close();
//        serverSocket.close();
        new MyJedisDemo().send("money", "wenxin", "10000");
    }

    public MyJedisDemo() {
        try {
            socket = new Socket("127.0.0.1", 6379);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void send(String key, String filed, String value) throws IOException {
        StringBuffer sb = new StringBuffer();
        sb.append("*4").append("\n");
        sb.append("$4").append("\n");
        sb.append("HSET").append("\n");
        sb.append("$").append(key.length()).append("\n");
        sb.append(key).append("\n");
        sb.append("$6").append("\n");
        sb.append("wenxin").append("\n");
        sb.append("$").append(value.length()).append("\n");
        sb.append(value).append("\n");
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        socket.close();

    }
}
